package dao.util;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.WebApplicationTemplateResolver;
import org.thymeleaf.web.IWebApplication;
import org.thymeleaf.web.IWebExchange;
import org.thymeleaf.web.servlet.JakartaServletWebApplication;

import java.io.IOException;
import java.util.Map;

public class ThymeleafView {
    private static TemplateEngine engine;
    private static IWebApplication webApplication;

    private static synchronized void init(ServletContext servletContext){
        if(engine != null) return;
        webApplication = JakartaServletWebApplication.buildApplication(servletContext);
        WebApplicationTemplateResolver resolver = new WebApplicationTemplateResolver(webApplication);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheTTLMs(30000L);
        resolver.setCacheable(true);

        engine = new TemplateEngine();
        engine.setTemplateResolver(resolver);
    }

    public static void render(String templateName,
                               HttpServletRequest req,
                               HttpServletResponse resp,
                               Map<String, Object> model) throws IOException {
        init(req.getServletContext());
        resp.setContentType("text/html;charset=UTF-8");
        IWebExchange exchange = ((JakartaServletWebApplication) webApplication).buildExchange(req, resp);
        WebContext ctx = new WebContext(exchange);
        if(model != null){
            for(Map.Entry<String, Object> e : model.entrySet()){
                ctx.setVariable(e.getKey(), e.getValue());
            }
        }
        engine.process(templateName, ctx, resp.getWriter());
    }
}